<template>
  <div id="dialogWindowConfig">
    <el-dialog
      :title="dialogData.type === 'add' ? '新增配置管理' : '编辑配置管理'"
      :visible.sync="dialogData.isShow"
      center
      width="550px"
    >
      <el-form ref="ruleForm" :model="formData" :rules="rules">
        <el-form-item label="直播频道号：" prop="channelIds">
          <ul class="node">
            <li v-for="(item, index) in formData.channelIds" :key="index">
              <el-input
                v-model="formData.channelIds[index]"
                size="mini"
                maxlength="9"
                style="width:100px;"
                @input="validateSort($event, index)"
              ></el-input>
              <span
                class="handleBtn"
                @click="addChannelId"
                v-if="
                  formData.channelIds.length - 1 === index &&
                    formData.channelIds.length !== 10
                "
                ><i class="el-icon-plus"></i
              ></span>
              <span
                class="handleBtn"
                @click="deleteChannelId(index)"
                v-if="formData.channelIds.length !== 1"
                ><i class="el-icon-minus"></i
              ></span>
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="配置所在端：" prop="terminals">
          <el-checkbox-group v-model="formData.terminals">
            <el-checkbox
              v-for="item in terminalList"
              :key="item.dictValue"
              :label="item.dictValue"
              >{{ item.dictLabel }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <!-- 错误提示 -->
      <div class="errorRemind">
        <span v-if="isExist">{{ isExist }}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="confirmLabel('ruleForm')">
          生成直播间管理
        </el-button>
        <el-button type="success" plain @click="dialogData.isShow = false">
          取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addWindow, windowDetail, editWindow } from '@/api/system/window'
import { sysNormalDisable } from '@utils/dictionariesFunc'
export default {
  props: ['dialogData'],
  data() {
    var validateChannelId = (rule, value, callback) => {
      if (value.length === 1 && value[0] === '') {
        callback(new Error('请输入频道号'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        channelIds: [''],
        terminals: []
      },
      isExist: '',
      terminalList: [], //字典配置端
      rules: {
        channelIds: [
          { required: true, validator: validateChannelId, trigger: 'blur' }
        ],
        terminals: [
          { required: true, message: '请选择配置端', trigger: 'change' }
        ]
      }
    }
  },
  async mounted() {
    //获取配置端字典
    this.terminalList = await sysNormalDisable('live_room_window_terminal')
    //配置详情
    const { id } = this.dialogData
    if (id) {
      windowDetail({ id }, (res) => {
        this.formData.channelIds = res.channelIds
        this.formData.terminals = res.terminals
      })
    }
  },
  methods: {
    //频道号只能为数字
    validateSort(val, index) {
      this.formData.channelIds[index] = val.replace(/[^\d]/g, '')
    },
    //添加频道号
    addChannelId() {
      if (!this.formData.channelIds.slice(-1)[0]) {
        this.$message.warning('请填写后再添加')
        return
      }
      const isRepeat = this.validateRepeat()
      if (isRepeat) return
      this.formData.channelIds.push('')
    },
    validateRepeat() {
      let lastItem = this.formData.channelIds.slice(-1)[0]
      for (let i = 0; i < this.formData.channelIds.length - 1; i++) {
        if (lastItem === this.formData.channelIds[i]) {
          this.$message.warning(`${lastItem}频道号已存在，请勿重复添加`)
          return true
        }
      }
    },
    //删除文字标签
    deleteChannelId(index) {
      this.formData.channelIds.splice(index, 1)
    },
    //确定
    confirmLabel(formName) {
      const isRepeat = this.validateRepeat()
      if (isRepeat) return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { id, type } = this.dialogData
          if (type === 'add') {
            addWindow(
              this.formData,
              (res) => {
                this.$message.success('添加成功')
                this.$emit('refresh')
                this.dialogData.isShow = false
              },
              (err) => {
                this.isExist = err.message
              }
            )
          } else {
            editWindow(
              id,
              this.formData,
              (res) => {
                this.$message.success('修改成功')
                this.$emit('refresh')
                this.dialogData.isShow = false
              },
              (err) => {
                this.isExist = err.message
              }
            )
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.node {
  width: 280px;
  margin-left: 105px !important;
  .handleBtn {
    display: inline-block;
    width: 25px;
    height: 25px;
    background-color: #1dc8a4;
    color: #fff;
    text-align: center;
    line-height: 25px;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
  }
}
:deep(.el-form-item__error) {
  left: 105px !important;
}
.errorRemind {
  color: #d9001b;
  margin-bottom: 20px;
  text-align: center;
}
</style>
